package com.atguigu.gmall.product.biz.impl;/*
 * @author: XueYouPeng
 * @time: 23.7.14 下午 7:19
 */

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.cache.anno.GmallCache;
import com.atguigu.gmall.common.constant.GmallConstant;
import com.atguigu.gmall.product.biz.BaseCategoryBizService;
import com.atguigu.gmall.product.mapper.BaseCategory1Mapper;
import com.atguigu.gmall.product.vo.CategoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class BaseCategoryBizServiceImpl implements BaseCategoryBizService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private ConcurrentHashMap<String,List<CategoryVo>> cacheMap = new ConcurrentHashMap<String,List<CategoryVo>>();


    @Override
    //直接用封装好的aop来进行redis的调用
    @GmallCache(cacheKey = "allCategory")
    public List<CategoryVo> findAllCategoryTree() {

        List<CategoryVo> categoryVos = baseCategory1Mapper.findAllCategoryTree();
        return categoryVos;
    }

    public List<CategoryVo> findAllCategoryTreeRedisTemplate() {

        //从Redis缓存中进行命中
        String allCategoryJSON = redisTemplate.opsForValue().get(GmallConstant.REDIS_CATEGORY_KEY);
        if (!StringUtils.isEmpty(allCategoryJSON)){

            //证明从redis中查到了 判断是否为x
            if (GmallConstant.REDIS_NULL_VALUE.equalsIgnoreCase(allCategoryJSON)){
                log.info("从Redis缓存中查询到了数据...x");
                return null;
            }else {
                log.info("从Redis缓存中查询到了数据...");
                List<CategoryVo> categoryVoList = JSON.parseArray(allCategoryJSON, CategoryVo.class);
                return categoryVoList;
            }
        }

        log.info("从数据库中查询到了数据...");
        List<CategoryVo> categoryVos = baseCategory1Mapper.findAllCategoryTree();
        if (categoryVos!=null && categoryVos.size() > 0){
            redisTemplate.opsForValue().set(GmallConstant.REDIS_CATEGORY_KEY,JSON.toJSONString(categoryVos));
        }else {
            redisTemplate.opsForValue().set(GmallConstant.REDIS_CATEGORY_KEY,GmallConstant.REDIS_NULL_VALUE);
        }
        return categoryVos;
    }
}
